<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>将对象绑定为数组</title>

    <script src="https://cdn.bootcss.com/d3/5.15.1/d3.js"></script>
    <link href="https://cdn.bootcss.com/twitter-bootstrap/4.4.1/css/bootstrap.css" rel="stylesheet">
    <style>
        h1,
        h2,
        h3 {
            font-weight: bold;
        }

        .h-bar {
            text-align: right;
            margin-top: 2px;

        }

        .h-bar span {
            font-size: 14px;
            margin-right: 5px;
            color: white;
        }

        footer {
            font-size: 12px;
            background-color: #ddd;
            text-align: center;
        }

        footer p {
            height: 5ch;
            line-height: 5ch;
        }

    </style>
</head>

<body>
    <header>
        <h1 class="text-center my-5">数据绑定练习</h1>
    </header>
    <main>
        <section class="container">
            <h2 class="my-5">将对象绑定为数据</h2>
            <div class="row justify-content-center">
                <div class="col-md-8" id="objectStage">

                </div>
            </div>
        </section>
    </main>

    <footer class="container-fluid mt-5 fixed-bottom">
        <p>《网络编辑与制作》课程练习</p>
    </footer>
    <script>
        var data = [
            { width: 10, color: 23 }, { width: 15, color: 33 },
            { width: 30, color: 40 }, { width: 50, color: 60 },
            { width: 80, color: 22 }, { width: 65, color: 10 },
            { width: 55, color: 5 }, { width: 30, color: 30 },
            { width: 20, color: 60 }, { width: 10, color: 90 },
            { width: 8, color: 10 }
        ];

        var colorScale = d3.scaleLinear()//设定颜色比例尺
            .domain([0, 100])
            .range(["#add8e6", "blue"]);

        function render(data) {
            d3.select("body").select("#objectStage").selectAll("div.h-bar")
                .data(data)//update
                .enter() //enter
                .append("div")
                .attr("class", "h-bar")
                .append("span");

            // d3.selectAll("div.h-bar")
            //     .data(data)
            //     .exit().remove();

            d3.selectAll("div.h-bar")
                .data(data)
                .attr("class", "h-bar")
                .style("width", function (d) {
                    return (d.width * 5) + "px";
                })
                .style("background-color", function (d) {
                    return colorScale(d.color);
                })
                .select("span")
                .text(function (d) {
                    return d.width;
                });
        }

        function randomValue() {
            return Math.round(Math.random() * 100);
        }

        setInterval(function () {
            data.shift();
            data.push({ width: randomValue(), color: randomValue() });
            render(data);
        }, 1500);

        render(data);

    </script>

</body>

</html>
